package tij4.concurrent.exercise.ex19;

import java.awt.*;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*
    修改了 OrnamentalGarden 使其使用interrupt()方法结束
 */
class Count{
    private int count = 0;
    private Random random = new Random(46);

    public synchronized int increment(){    //直接定义为synchronize
        int temp = count;
        if (random.nextBoolean())
            Thread.yield();
        return (count = ++temp);
    }

    public synchronized int value() {       //自己定义为synchronize
        return count;
    }
}

class CountManager implements Runnable{
    private static Count count = new Count();
    private int number;
    private final int id;

    public CountManager(int id) {
        this.id = id;
    }

    public synchronized int getValue() {
        return count.value();
    }

    public synchronized int increment() {
        number ++;
        count.increment();
        System.out.println("#:"+id+" number:"+number+" total:"+count.value());
        return number;
    }

    @Override
    public void run() {
        try {
            while (true) {
                increment();
                TimeUnit.MILLISECONDS.sleep(2);
            }
        }catch (InterruptedException e){
            System.out.println("InterruptedException");
        }
    }
}


public class Ex19 {
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(new CountManager(i));
        }
        TimeUnit.SECONDS.sleep(3);
        executorService.shutdownNow();
    }
}
